package com.example.practice2023.service;

import com.example.practice2023.mapper.UserMapper;
import com.example.practice2023.pojo.User;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: UserService
 * Package: com.example.practice2023.service
 * Description:
 *
 * @Author hyx
 * @Create 2023/7/3 0:16
 * @Version 1.0
 */
@Service
public class UserService {
    @Resource
    private UserMapper userMapper;

    public Map<String, Object> insertStaff(User user) {
        Map<String, Object> map = new HashMap<>();
        String password = user.getPassword();
//         这里手动加密5次 MD5
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        md5Pass = DigestUtils.md5DigestAsHex(md5Pass.getBytes(StandardCharsets.UTF_8));
        md5Pass = DigestUtils.md5DigestAsHex(md5Pass.getBytes(StandardCharsets.UTF_8));
        md5Pass = DigestUtils.md5DigestAsHex(md5Pass.getBytes(StandardCharsets.UTF_8));
        md5Pass = DigestUtils.md5DigestAsHex(md5Pass.getBytes(StandardCharsets.UTF_8));
        user.setPassword(md5Pass);
        user.setRegisterTime(new Timestamp(System.currentTimeMillis()));  // util Date  sql Date  Time  Timestamp
        userMapper.insertStaff(user);
        map.put("code", 200);
        map.put("msg", "新增用户成功");
        map.put("data", user);
        return map;
    }

    public Map<String, Object> selectByPage(int page, int limit, User user) {
        int index = (page - 1) * limit;   // 通用性的分页起始下标计算
        List<User> userList = userMapper.selectByPage(index, limit, user.getUsername(), user.getType(), user.getPhone(), user.getStatus());
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", userMapper.selectAllCount(user.getUsername(), user.getType(), user.getPhone(), user.getStatus()));   // 通过数据库全查功能，把所有的记录个数统计出来
        map.put("data", userList);
        return map;
    }

    public Map<String, Object> updateStaff(User user) {
        Map<String, Object> map = new HashMap<>();
        user.setUpdataTime(new Timestamp(System.currentTimeMillis()));
        System.out.println(user.getUpdataTime());
        userMapper.updateStaff(user);
        map.put("code", 200);
        map.put("msg", "更新用户成功");
        map.put("data", user);
        return map;
    }

    public Map<String, Object> deleteStaff(Integer id) {
        Map<String, Object> map = new HashMap<>();
        userMapper.deleteStaff(id);
        map.put("code", 200);
        map.put("msg", "删除用户成功");
        map.put("id", id);
        return map;
    }

}
